/* eslint-disable array-callback-return */
/* eslint-disable no-case-declarations */
// Import Swiper React components
import { useState, useMemo, useRef, useEffect } from 'react';
import {
  ArrowUpOutlined,
  CaretRightFilled,
  CaretRightOutlined,
  CloseOutlined,
  DoubleRightOutlined,
  LoadingOutlined,
  PictureFilled,
  PlusOutlined,
  QrcodeOutlined,
  UserAddOutlined,
} from '@ant-design/icons';
import {
  Avatar,
  Button,
  message,
  Drawer,
  Progress,
  theme,
  Tooltip,
  Tag,
  Collapse,
  Row,
  Col,
  Tabs,
  Empty,
  Timeline
} from 'antd';
import Limit from '../Limit';
// Import Swiper styles
import { difftime, difftimes } from '@/utils/time';
import dayjs from 'dayjs';
import { Fade } from 'react-reveal';
import ReplyCard from './ReplyCard';
import { ProFormSelect } from '@ant-design/pro-components';
import useCurrentUser from '@/utils/useCurrentUser';
import './index.less';
import { useRequest } from 'ahooks';
import { doFetch, getFetch } from '@/utils/doFetch';
import { Badge } from 'antd';
import useMyProjectList from '@/utils/useMyProjectList';
import { toPng } from 'html-to-image';
import useProjectList from '@/utils/useProjectList';
import Tagpreview from '../Tagadder/tagpreview';
import { statusConf } from '@/utils/global'
import { v4 as uuidv4 } from 'uuid';
import ItemCard from '../ItemCard';
import IconFont from '../IconFont';
import SvgDot from '../SvgDot';
import { items } from '@/utils/global';

import FileCard from '../FileCard';


const Users = ({ project = {}, activeUserIdList = [], token, data }) => {

  const formatdata = useMemo(() => data ? [
    data?.find((it) => it?.id === project?.projectUserId),
    ...[
      ...data?.filter(
        (it) =>
          it?.id !== project?.projectUserId && activeUserIdList.includes(it?.id.toString()),
      ),
      ...data?.filter(
        (it) =>
          it?.id !== project?.projectUserId && !activeUserIdList.includes(it?.id.toString()),
      ),
    ],
  ] : [], [data])

  return <div style={{ display: 'flex' }}>
    <div
      className='griders'
    >
      {data?.length > 0 && formatdata.map((it, i) => {
        const isMine = it?.isMaster === 1; //it?.id === project?.projectUserId;
        return <div key={it?.id} style={{ backgroundColor: token.colorOppsites }}>
          <Badge count={isMine ? <IconFont type='icon-manager' rotate={30} /> : 0}>
            <Avatar
              src={it?.headUrl}
              size={"default"}
              style={{
                cursor: 'pointer',
                backgroundColor: token.colorBgContainer,
                color: token.colorText,
              }}
            >
              {it?.name?.charAt(0)}
            </Avatar>
          </Badge>
          <div className="columns" style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
            <span className='oneline'>
              {it?.name} {it?.projectRoleId === 2 ? '服务' : it?.projectRoleId === 3 ? '审批' : '-'}
            </span>
            <a style={{ fontSize: 12 }} href={`tel:${it?.telephone}`}>{it?.telephone}</a>
          </div>
        </div>
      })}

    </div>
  </div>
}


const Timez = ({ activeKeys, item, curkey, currentUser }) => {

  const { token } = theme.useToken();


  const { data, loading } = useRequest(
    async () => {
      if (!activeKeys.includes(curkey)) return;
      let res = await getFetch({ url: '/itemMsg', params: { itemId: item?.id } });
      let result = await getFetch({ url: '/itemResume', params: { itemId: item?.id } });

      const alldata = [...(res?.data?.dataList ?? []), ...(result?.data?.dataList ?? [])]?.map(it => ({
        ...it,
        userName: it?.userName ?? it.createUserName,


      }))?.sort((a, b) => dayjs(b.createTime).valueOf() - dayjs(a.createTime).valueOf());

      return alldata;
    },
    {
      refreshDeps: [curkey, item, activeKeys],
    },
  );



  return <div style={{ margin: "6px 0" }}>
    {
      data && <Timeline
        items={
          data.map((it, i) => ({
            color: i === 0 ? "blue" : "gray",
            children: <div>
              <div>
                <b>{dayjs(it?.createTime)?.format("MM-DD HH:mm")}</b>
                <b style={{ padding: "0 6px", color: token.colorPrimary }}>{it?.userName}</b>
                <span>{it?.info ?? "给节点任务添加了留言"}</span>
              </div>
              {
                !it?.info && <ReplyCard
                  {...it}
                  key={i}
                  currentUser={currentUser}
                  token={token}
                />
              }

            </div>
          }))
        }
      />
    }

  </div>
}

const Mission = ({ it, activeKey, setNum, currentUser }) => {
  const { token } = theme.useToken();
  const {
    colorOppsites
  } = token;

  let res = it?.itemList ?? [];
  useEffect(() => {
    setNum(s => {
      const news = [...s];
      [0, 1, 2, 5]?.map(i => news[i] = res?.filter(s => s.status === i)?.length)
      news[6] = res?.length
      return news
    })
  }, [res]);


  const thisdatas = res?.filter(s => {
    if (activeKey === 6) {
      return true;
    } else {
      return s.status === activeKey
    }
  })

  // <Row gutter={[12, 12]}>
  //   {
  //     thisdatas?.map((it, i) => {
  //       return <Col key={i} {...colc} onClick={() => {
  //         setInitialState(s => ({
  //           ...s,
  //           drawerAll: {
  //             ...s.drawerAll,
  //             item: it,
  //             open: true,
  //           }
  //         }))
  //       }}>
  //         {
  //           <ItemCard item={it} bg={colorOppsites}></ItemCard>
  //         }
  //       </Col>
  //     })
  //   }
  //   {
  //     thisdatas?.length === 0 && <Col span={24}>
  //       <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
  //     </Col>
  //   }
  // </Row>

  const [activeKeys, setActiveKeys] = useState();




  return <>
    <Collapse
      bordered={false}
      expandIcon={({ isActive }) => <DoubleRightOutlined rotate={isActive ? 90 : 0} style={{ opacity: 0.5 }} />}
      expandIconPosition="right"
      style={{
        background: token.colorBgContainer,
      }}
      activeKey={activeKeys}
      onChange={setActiveKeys}
      items={thisdatas?.map((it, i) => {
        return {
          key: activeKey + "s" + i,
          label: <div className='columns' style={{ gap: 6 }}>
            <b style={{ fontSize: 16 }}>
              {it?.missionName}
            </b>
            <span style={{ fontSize: 14 }}>预计完成时间: {it?.planEnd}</span>
          </div>,
          extra: <div className='columns' style={{ gap: 6, alignItems: "flex-end" }}>
            <span style={{ opacity: 0.5 }}>任务动态</span>
            <div className='center'>
              <SvgDot style={{ flexShrink: 0 }} size={12} color={items[it?.status]?.color} />
              <span style={{ fontSize: 14, color: items[it?.status]?.color, paddingLeft: 6 }} className='oneline'>
                {items[it?.status]?.statusName}
              </span>
            </div>
          </div>,
          children: <Timez currentUser={currentUser} activeKeys={activeKeys} item={it} curkey={activeKey + "s" + i} />,
          style: {
            marginBottom: 12,
          }
        }

      })}
      defaultActiveKey={['1']}
    />
    {
      thisdatas?.length === 0 && <Col span={24}>
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
      </Col>
    }
  </>
}

const ProjectDetail = ({ curid }) => {
  const domRef = useRef();
  const { initialState: { activeUserIdList, currentUser } } = useProjectList();
  const { token } = theme.useToken();
  const {
    colorText,
    colorPrimary,
    colorBgThird,
    colorBgFourth,
    colorBgContainer,
    colorOppsites
  } = token;

  const [collapse, setCollapse] = useState(false);

  const { data, loading } = useRequest(async () => {
    let res = await getFetch({ url: "/project/detail/" + curid, params: {} });
    return res?.data?.data;
  }, {
    refreshDeps: [curid],
  })

  const it = useMemo(() => {
    return data ?? {};
  }, [data])

  const style = {
    backgroundColor: colorOppsites,
    cursor: 'default',
    gap: 6,
    justifyContent: 'center',
    padding: "12px 16px",
    overflow: 'hidden',
    display: 'flex',
    borderRadius: 8,
    fontSize: 14,
    backdropFilter: "blur(4px)",
    width: "100%",
    height: "100%"
  }

  const strokeColor = useMemo(() => {
    return currentUser.theme === 'light' ? {
      "0%": '#fec163',
      '70%': '#ff4800',
    } : {
      "0%": '#17ead9',
      '70%': '#6078ea',
    }
  }, [currentUser.theme]);

  const [activeKey, onChange] = useState(6);
  const [num, setNum] = useState([]);

  const mprops = {
    it,
    setNum,
    currentUser
  }

  const items = [
    {
      key: 6,
      label: <Badge count={num[6] ?? 0} size='small' color="blue"><span>全部</span></Badge>,
      children: <Mission activeKey={6} {...mprops}></Mission>,
    },
    {
      key: 0,
      label: <Badge count={num[0] ?? 0} size='small' color="blue"><span>未开始</span></Badge>,
      children: <Mission activeKey={0} {...mprops}></Mission>,
    },
    {
      key: 1,
      label: <Badge count={num[1] ?? 0} size='small' color="blue"><span>进行中</span></Badge>,
      children: <Mission activeKey={1} {...mprops}></Mission>,
    },
    {
      key: 5,
      label: <Badge count={num[5] ?? 0} size='small' color="blue"><span>待审核</span></Badge>,
      children: <Mission activeKey={5} {...mprops}></Mission>,
    },
    {
      key: 2,
      label: <Badge count={num[2] ?? 0} size='small' color="blue"><span>已完成</span></Badge>,
      children: <Mission activeKey={2} {...mprops}></Mission>,
    },
  ];

  return (
    <div
      ref={domRef}
      id="mobileshare"
      style={{
        width: '100%',
        background: 'transparent',
        borderRadius: 12,
        color: colorText,
        marginRight: -6
      }}
    >
      <Drawer
        classNames={{
          header: {
            display: "none"
          }
        }}
        onClose={() => {
          setCollapse(false)
        }}
        open={collapse}
        height={'80%'}
        closable={false}
        style={{
          borderRadius: "0 0 12px 12px",
          padding: 12,
          overflow: "hidden",
        }}
        placement='top'
      >
        <div style={{ ...style, flexDirection: "column", justifyContent: "flex-start" }}>
          <div className="spread">
            <b>
              项目标准
            </b>
            <Button onClick={() => {
              setCollapse(false);
            }} icon={<CloseOutlined />}>
            </Button>
          </div>

          <div style={{ flex: 1, overflow: "hidden" }}>
            <Limit
              content={it?.notice || '暂无公告'}
              style={{ width: "100%", height: 'auto', margin: 0 }}
            ></Limit>
          </div>
        </div>
      </Drawer>

      <div
        className="columns"
        style={{
          gap: 16,
          padding: 0,
        }}
      >
        <div
          style={{ ...style, justifyContent: "flex-start" }}
        >
          <div className="columns" style={{ width: "100%", gap: 6 }}>
            <div className="spread gap6" style={{ paddingTop: 4 }}>
              <b style={{ display: "block", fontSize: 16, }}>{it?.projectName}</b>
              <Tag color={statusConf[it?.status]?.color} style={{ margin: 0 }}>{statusConf[it?.status]?.text}</Tag>
            </div>
            <div className="spread" style={{ width: "100%", alignItems: "flex-end" }}>
              <p style={{ opacity: 0.5, fontSize: 14, margin: "0 0 0 0px", textAlign: "left" }}>
                服务类型: &nbsp;{it?.createUserName} 创建于 {difftime(dayjs(), dayjs(it?.createTime))}
              </p>
            </div>
            <div className="spread" style={{ width: "100%", alignItems: "flex-end" }}>
              <p style={{ opacity: 0.5, fontSize: 14, margin: "0 0 0 0px", textAlign: "left" }}>
                服务期限:  &nbsp;{dayjs(it?.createTime).format("YYYY-MM-DD")} - {it?.deadline}
              </p>
            </div>

            <div className="spread" style={{ width: "100%", alignItems: "flex-end", gap: 6 }}>
              <p style={{ opacity: 0.5, fontSize: 14, margin: "0 0 0 0px", textAlign: "left" }}>
                服务进度:
              </p>
              <Progress
                style={{ margin: 0, opacity: 0.7, flex: 1 }}
                percent={it.allItemCount !== 0 ? parseInt(it.finishItemCount * 100 / it.allItemCount) : 0}
                size="small"
                strokeColor={strokeColor}
                format={() => `${it.finishItemCount}/${it.allItemCount}`}
              />
            </div>
            <div className='center' style={{ marginTop: 4 }}>
              <Button size='small' type='link' onClick={() => {
                setCollapse(!collapse)
              }}>查看标准</Button>
            </div>
          </div>
        </div>


        <h2 className="ltitle" style={{ marginTop: -6 }}>
          节点任务
        </h2>

        <Tabs size='small' activeKey={activeKey} items={items} onChange={onChange} />

        <h2 className="ltitle">
          参与人员
        </h2>
        <Users readonly={true} project={it} token={token} activeUserIdList={activeUserIdList} data={it?.userList} currentUser={currentUser}></Users>
      </div>
    </div>
  );
};

export default ProjectDetail
